﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZdSoft.Model;
using ZdSoft.Core;
using ZdSoft.IDAL;
using ZdSoft.Web.OnlineStudy.Apps;

namespace ZdSoft.Web.OnlineStudy.Controllers
{
    public class RoleController : BaseController
    {
        public ActionResult Index (int pageIndex=1)
        {
            int count = 0;
            //查询指定索引页的角色信息
            IList<Role> list = Container.Instance.Resolve<IRoleDAL>().GetPaged(null, null, pageIndex, PagerHelper.PageSize, out count);
            //将结果转换为pagelist对象，以供分业控件使用
            PageList<Role> pagelist = list.ToPageList<Role>(pageIndex, PagerHelper.PageSize, count);
            return View(pagelist);
        }

        [HttpGet]
        public ViewResult Create()
        {
            //实例化模型对象
            Role role = new Role();
            return View(role);
        }

        [HttpPost]

        public ActionResult Create(Role role)
        {
            //确定模型验证是否通过
            if(ModelState.IsValid)
            {
                //调用事物逻辑层进行角色创建
                Container.Instance.Resolve<IRoleDAL>().Create(role);
                return RedirectToAction("Index");
            }
            return View();//停留在原始页面
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            //根据角色信息ID查询角色信息
            Role model = Container.Instance.Resolve<IRoleDAL>().Get(id);
            //以模型传值得方式将model传递到Create视图中显示
            return View("Create", model);
        }
        [HttpPost]
        public ActionResult Edit(Role model)
        {
            if(ModelState.IsValid)
            {
                Container.Instance.Resolve<IRoleDAL>().Update(model);

                return RedirectToAction("Index");
            }
            return View("Create", model);//停留在当前页面
        }
        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        public ActionResult SwitchStatus(int id)
        {
            Role model = Container.Instance.Resolve<IRoleDAL>().Get(id);

            model.IsActive = !model.IsActive;//操作一次就取反一次

            Container.Instance.Resolve<IRoleDAL>().Update(model);
            return RedirectToAction("Index");//返回到主页
        }

        public ActionResult Delete(int id)
        {
            Role model = Container.Instance.Resolve<IRoleDAL>().Get(id);
            //判断角色是否分配了给用户，由于级联关系，所以只有没有分配给用户的时候才能够删除
            if(model.Users==null||model.Users.Count==0)
                Container.Instance.Resolve<IRoleDAL>().Delete(model);
            return RedirectToAction("Index");//返回到主界面
        }
    }
}